import Utils from "../common/Util";
import GameManager from "../common/GameManager";
import PopUpManager from "../common/PopUpManager";
import { GameConfig } from "../common/GameConfig";
import { lang_zh } from "../i18n/zh";
import Facebook from "../Facebook/Facebook";
import FacebookStorage from "../Facebook/FacebookStorage";
import EventUtils from "../gmbox/EventUtils";

const { ccclass, property } = cc._decorator;

@ccclass
export default class PauseLayer extends cc.Component {
    @property(cc.Node)
    scoreNode: cc.Node;

    @property(cc.Node)
    closeBtn: cc.Node;

    @property(cc.Node)
    shareBtn: cc.Node;

    @property(cc.Node)
    rankBtn: cc.Node = null;

    @property(cc.Label)
    curRank: cc.Label = null;

    @property(cc.RichText)
    passPlayerCount: cc.RichText = null;

    private musicBtnState = null;
    private _manager: GameManager;
    private myNewScore: number = 0;
    private _curScore: number = 0;

    onLoad() {
        this.musicBtnState = 0;
        this._manager = GameManager.getInstance();

        Utils.SetNodeText(this.scoreNode, 0);

        //上报分数
        if (typeof gmbox != 'undefined') {
            gmbox.updateGameRank({
                value: Number(this._curScore),
                type: 1
            })
        }


    }

    onEnable() {
        this._curScore = this._manager.gameData.GetCurScore();
        GameManager.getInstance().eventCenter.DispatchEvent("gameover");
        EventUtils.logEvent("gameover")

        // if (GameConfig.gameType == "runtime") {
        //     gmbox.platformCall({
        //         type: 3,
        //         gameId: "10115540993560001011",
        //         score: this._curScore,
        //         success: (res) => {
        //             console.log('排行版返回');
        //             console.log(res);
        //             if (res.code != 0) {
        //                 this.curRank.string = `${lang_zh.no_rank[GameConfig.languages]}`;
        //             } else {
        //                 this.curRank.string = `${lang_zh.world_rank[GameConfig.languages]}:No.${res.data.rankId}`;
        //             }
        //         }
        //     })
        // }

        if (Facebook.IsFBInit()) {
            FacebookStorage.LoadDataFormFB(['highestScore'], (data) => {
                let oldHighestScore = data['highestScore'];
                if (!oldHighestScore) {
                    oldHighestScore = 0;
                }
                this.refreshScore(oldHighestScore, this._curScore);
            })

            Facebook.FBRank.SetScoreToGloalRank(this._curScore);
            cc.log("SetScoreToGloalRank : " + this._curScore)
        } else {
            let oldHighestScore = GameManager.getInstance().gameLocalData.ReadLocalHighestScore();
            this.refreshScore(oldHighestScore, this._curScore);
        }


        this.passPlayerCount.string = this.getPassPlayerCount() + '';

        Utils.addEventListener(this.closeBtn, this.closeBtnClicked.bind(this));
        Utils.addEventListener(this.shareBtn, this.shareBtnClicked.bind(this));
        this.rankBtn.on(cc.Node.EventType.TOUCH_START, this.openRankPage, this);

        this.myNewScore = this._curScore;
        this.schedule(this.runChangeUserScore, .1);


    }

    onDisable() {
        Utils.removeEventListener(this.closeBtn);
        Utils.removeEventListener(this.shareBtn);
        this.rankBtn.off(cc.Node.EventType.TOUCH_START, this.openRankPage, this);
    }

    start() {
        this.showLayer();
    }

    showLayer() {
        this.node.active = true;
        this.node.scaleX = 1;
        this.node.scaleY = 1;
        PopUpManager.Show_ScaleEffect(this.node, 0.2);
    }

    removeLayer(isEffect) {
        isEffect = false;
        if (isEffect) {
            PopUpManager.Remove_ScaleEffect(this.node, 0.2);
        } else {
            if (this.node.isValid) {
                // this.node.destroy();
                this.node.removeFromParent();
            }
        }
    }

    //点击关闭按钮
    closeBtnClicked() {
        GameManager.getInstance().audioManager.PlayBtnSound();
        this.removeLayer(true);
        GameManager.getInstance().eventCenter.DispatchEvent("gameover");
        EventUtils.logEvent("game_restart", {
            from: "gameover"
        })
    }

    /**
     * 分享
     */
    shareBtnClicked() {
        // Facebook.Share(null, Facebook.SHARE_IMAGE_BASE64);
        Facebook.ChooseAsync();
    }

    runChangeUserScore() {
        //开始时的分数
        var tempScore = 0;
        //结束时的分数
        var endedScore = this._curScore;
        //用户增加的成绩
        var changedScore = endedScore - tempScore;
        //分数增加的时间系数
        var changeTime = 0.08;
        if (changedScore != 0) {
            if (endedScore == 0) {
                tempScore -= this.myNewScore * changeTime >> 0;
            } else {
                tempScore += this.myNewScore * changeTime >> 0;
            }

            if (endedScore < 0 && endedScore - tempScore >= 0) {
                tempScore = endedScore;
            }
            if (endedScore > 0 && tempScore - endedScore >= 0) {
                tempScore = endedScore;
            }
            this.myNewScore = tempScore + this.myNewScore;
            if (Math.abs(this.myNewScore - changedScore) < 10) {
                Utils.SetNodeText(this.scoreNode, changedScore);
                this.unschedule(this.runChangeUserScore);
            } else {
                Utils.SetNodeText(this.scoreNode, tempScore);
            }
        }
    }

    private refreshScore(old: number, current: number) {
        console.log("refreshScore old = " + old + ", current = " + current);
        if (old >= current) return;
        if (Facebook.IsFBInit()) {
            FacebookStorage.SaveDataToFB({
                "highestScore": current
            }, () => {
                GameManager.getInstance().eventCenter.DispatchEvent("highest_score_changed");
            })
        } else {
            GameManager.getInstance().gameLocalData.SaveLocalHighestScore(current);
            GameManager.getInstance().eventCenter.DispatchEvent("highest_score_changed");
        }
    }

    /**
   * 打开排行榜
   */
    private _rulePage: cc.Node;
    private openRankPage() {
        EventUtils.logEvent("click_rank", {
            from: "gameover"
        })
        Utils.GetPrefab("prefab/VerScrollview.prefab", (prefab) => {
            if (prefab && (!this._rulePage || !this._rulePage.parent)) {
                this._rulePage = cc.instantiate(prefab);
                // this.node.removeAllChildren();
                this.node.addChild(this._rulePage);
            }
        }, this)
    }

    private getPassPlayerCount(): string {
        let score = this._curScore;
        if (score == 0) {
            return "";
        } else if (score >= 1 && score <= 99) {
            return lang_zh.overtakePlayers0[GameConfig.languages].replace("xxx", Utils.RandomNum(1, 50) + "");
        } else if (score >= 100 && score <= 999) {
            return lang_zh.overtakePlayers0[GameConfig.languages].replace("xxx", Utils.RandomNum(50, 100) + "");
        } else if (score >= 1000 && score <= 9999) {
            return lang_zh.overtakePlayers1[GameConfig.languages].replace("xxx", Utils.RandomNum(500, 1000) + "");
        } else if (score >= 10000 && score <= 99999) {
            return lang_zh.overtakePlayers1[GameConfig.languages].replace("xxx", Utils.RandomNum(5000, 10000) + "");
        } else if (score >= 100000 && score <= 999999) {
            return lang_zh.overtakePlayers2[GameConfig.languages].replace("xxx", Utils.RandomNum(50000, 100000) + "");
        } else if (score >= 1000000 && score <= 9999999) {
            return lang_zh.overtakePlayers2[GameConfig.languages].replace("xxx", Utils.RandomNum(100000, 10000000) + "");
        } else if (score >= 10000000 && score <= 99999999) {
            return lang_zh.overtakePlayers3[GameConfig.languages].replace("xxx", Utils.RandomNum(100000, 10000000) + "");
        } else if (score >= 100000000) {
            return lang_zh.overtakePlayers3[GameConfig.languages].replace("xxx", Utils.RandomNum(100000, 10000000) + "");
        }
    }
}